<?php

namespace iBrand\Component\Purchase\Repositories\Eloquent;

use iBrand\Component\Goods\Models\GoodsProduct;
use iBrand\Component\Purchase\Models\StockRecord;
use iBrand\Component\Purchase\Repositories\StockRecordRepository;
use Prettus\Repository\Eloquent\BaseRepository;

class StockRecordRepositoryEloquent extends BaseRepository implements StockRecordRepository
{

	public function model()
	{
		return StockRecord::class;
	}

	public function addStockRecord()
	{
		// TODO: Implement addStockRecord() method.
	}

	public function getCurrentStock($shop_id, $item_id, $item_type)
	{
		$stock = $this->findWhere(['shop_id' => $shop_id, 'item_id' => $item_id, 'item_type' => $item_type]);
		if ($stock && $stock->count() > 0) {
			return $stock->sum('change_count');
		}

		return 0;
	}

	public function getStockRecordPaginate(array $where, array $_where, array $with = [], array $ids = [], $limit = 20)
	{
		$query = $this->scopeQuery(function ($query) use ($where, $_where, $with, $ids) {
			if (!empty($where)) {
				foreach ($where as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($_where)) {
				foreach ($_where as $key => $value) {
					if (is_array($value)) {
						list($operate, $va) = $value;
						$query = $query->where($key, $operate, $va);
					} else {
						$query = $query->where($key, $value);
					}
				}
			}

			if (!empty($ids)) {
				$query = $query->whereIn('item_id', $ids);
			}

			if (!empty($with)) {
				foreach ($with as $value) {
					$query = $query->with($value);
				}
			}

			return $query->where('item_type', GoodsProduct::class)->orderBy('created_at', 'desc');
		});

		if ($limit) {
			return $query->paginate($limit);
		} else {
			return $query->all();
		}
	}
}